package com.gong.springmvc;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Arrays.stream(cookies).forEach(cookie -> System.out.println(cookie.getName() + " : " + cookie.getValue()));
        }
        return "获取 cookie 成功";
    }


    @RequestMapping("/getCookie1")
    public String getCookie1(@CookieValue("bite") String bite) {
        return "从cookie中获取值 bite :" + bite;
    }


    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        //从 cookie 中获取到了sessionID，根据sessionID获取session对象,如果没有获取到，会创建一个session对象
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        return "设置session成功";

    }


    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        //从 cookie 中获取到了sessionID，根据sessionID获取session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取name：" + name;

    }

    @RequestMapping("/getSession1")
    public String getSession1(HttpSession session) {
        //从 cookie 中获取到了sessionID，根据sessionID获取session对象
        String name = (String) session.getAttribute("name");
        return "从session中获取name：" + name;

    }


    @RequestMapping("/getSession2")
    public String getSession2(@SessionAttribute("name") String name) {
        return "从session中获取name：" + name;

    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }


    @RequestMapping("/getHeader1")
    public String getHeader1(@RequestHeader("User-Agent") String userAgent) {
        //String userAgent = request.getHeader("User-Agent");
        return userAgent;

    }
}
